using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Crossborder.Common.RedisModule;
using Crossborder.Common.Utility;
using Crossborder.Common.Utility.HttpHelper;
using Crossborder.Core.Const;
using Crossborder.Core.Cto;
using Crossborder.Core.Dto;
using Crossborder.Domian.Orders;

namespace Crossborder.Service.Orders
{
    public partial class OrderService
    {

        public async Task<HttpResponsion> AddOrderMaster(string userId, OrderMasterInputDto input)
        {
            using TransactionScope ts = new(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                List<ShoppingCartDto> carts = new();
                OrderMaster master = new()
                {
                    UserId = userId,
                    OrderNo = OrderNumberGenerator.OrderGeneratorFor24(),
                    InputDate = DateTime.Now,
                    Remark = input.Remark,
                    Address = input.Address,
                };
                master.Create();
                var redisKey = $"{RedisKeyName.IDX}:{RedisKeyName.USER_KEY}:{userId}";
                var keys = _Redis.GetRedisZSet(redisKey);
                foreach (var key in keys)
                {
                    var cart = await _Redis.GetHashMemoryAsync<ShoppingCartCto>(key);
                    var mapper = _Mapper.Map<ShoppingCartDto>(cart) ?? null;
                    if (mapper != null)
                    {
                        carts.Add(mapper);
                    }
                }
                // 添加主订单
                await _OrderMasterRepo.InsertAsync(master);
                // 添加订单详情
                await AddOrderDetail(carts, master.UserId);
                // 提交事务
                ts.Complete();

                // 删除购物车
                foreach (var key in keys)
                {
                    await _Redis.RemoveKeysAsync(key);
                }
                // 删除索引key
                await _Redis.RemoveKeysAsync(redisKey);

                return HttpHelper.Success("添加成功。");
            }
            catch (Exception ex)
            {

                ts.Dispose();
                return HttpHelper.Fail(ex.Message);
            }
        }
    }
}